package com.cah.project.core.dict.handler;

import cn.hutool.core.map.MapUtil;
import com.cah.project.core.dict.handler.business.IBusinessDictHandler;
import com.cah.project.core.dict.handler.dictData.AbstractDictDataHandler;
import com.cah.project.core.dict.handler.dictData.DefaultDictDataHandler;
import com.cah.project.core.dict.handler.dictData.IDictDataHandler;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 功能描述: 通过spring，将业务字典实现类注册到map中，方便使用 <br/>
 */
@Getter
@Component
public class DictHandlerAware implements ApplicationContextAware {

    private final Map<String, IBusinessDictHandler> handlerMap = new HashMap<>();
    // 设置默认实现
    private IDictDataHandler dictHandler = new DefaultDictDataHandler();

    /**
     * 功能描述: 获取应用上下文并获取相应的接口实现类 <br/>
     *
     * @param applicationContext 上下文
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //根据接口类型返回相应的所有bean
        Map<String, IBusinessDictHandler> map = applicationContext.getBeansOfType(IBusinessDictHandler.class);
        Set<Map.Entry<String, IBusinessDictHandler>> entries = map.entrySet();
        for(Map.Entry<String, IBusinessDictHandler> entry : entries) {
            this.handlerMap.put(entry.getValue().typeCode(), entry.getValue());
        }
        // 根据抽象类，返回字典实现
        Map<String, AbstractDictDataHandler> dictMap = applicationContext.getBeansOfType(AbstractDictDataHandler.class);
        if(MapUtil.isNotEmpty(dictMap)) {
            dictHandler = dictMap.entrySet().iterator().next().getValue();
        }
    }

}
